package com.mentalhealthplatform.global.log.login;

import com.mentalhealthplatform.global.log.dto.LoginLogDTO;
import com.mentalhealthplatform.utils.PagedResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;

@Service
public class LoginLogService {

    @Autowired
    private LoginLogRepository loginLogRepository;


    public PagedResponse<LoginLogDTO> getLoginLogs(String loginName, String loginStatus, String loginAddress,
                                                   String loginLocation, String browser, String operatingSystem,
                                                   LocalDateTime startDate, LocalDateTime endDate, int page, int size,
                                                   String sortField, String sortOrder) {

        // 默认排序：如果没有传入排序字段，则使用 loginTime 降序
        Sort sort = Sort.by(Sort.Order.desc("loginTime"));

        // 如果传入了排序字段和排序顺序
        if (sortField != null && !sortField.isEmpty()) {
            // 根据传入的排序顺序（ASC 或 DESC）构建排序对象
            Sort.Order order = "ASC".equalsIgnoreCase(sortOrder)
                    ? Sort.Order.asc(sortField)
                    : Sort.Order.desc(sortField);

            // 合并默认排序和传入的排序条件
            sort = Sort.by(order);
        }


        // 创建分页请求对象
        Pageable pageable = PageRequest.of(page, size, sort);

        // 调用 Repository 方法查询并返回分页数据
        Page<LoginLogDTO> pageResult = loginLogRepository.findLoginLogsWithFilters(
                loginName, loginStatus, loginAddress, loginLocation,
                browser, operatingSystem, startDate, endDate, pageable
        );

        // 使用 PagedResponse 封装分页数据
        return new PagedResponse<>(pageResult);
    }




    @Transactional
    public void deleteLoginLogsByIds(Long[] ids) {
        loginLogRepository.deleteByIdIn(ids);
    }

    @Transactional
    public void clearAllLoginLogs() {
        loginLogRepository.deleteAll();
    }

}
